<template>
  <div class="main">
    <Search :initData="initSearchData" @emitSearchData="getSearchData"></Search>
    <div class="content">
      <a-row :gutter="[16, 16]" style="position: relative;">
        <BarChart :span="16" :barData="barProductTypeLists"></BarChart>
        <Pie :span="8" :pieData="pieRepairFaultLists"></Pie>
      </a-row>
      <a-row :gutter="[16, 16]" style="position: relative;">
        <BarChart :span="16" :barData="barRepairStatusLists"></BarChart>
        <Pie :span="8" :pieData="pieRepairResultLists"></Pie>
      </a-row>
    </div>
  </div>
</template>

<script>
import Pie from "@/components/echart/pie";
import BarChart from "@/components/echart/bar";
import Search from "./components/search";

import { buildDateAxis, isNumber } from "@/unit/tool";
import api from "@/server/userConfig";

function transformTimeArray(lists) {
  return lists.map((item, index) => {
    let { name, value } = item;
    return {
      name,
      value
    };
  });
}

function formatResultType(value) {
  switch (value) {
    case 1:
      return "修好并入库";
    case 2:
      return "修好并返回现场";
    case 3:
      return "产品报废";
    default:
      break;
  }
}

function formatStatusType(value) {
  switch (value) {
    case 2:
      return "返厂中";
    case 3:
      return "已收货";
    case 4:
      return "已指派";
    case 5:
      return "维修收货";
    case 6:
      return "维修中";
    case 8:
      return "维修完成";
    case 10:
      return "返修完成";
    default:
      break;
  }
}

function buildPieData(pieDataLists, titleStr) {
  let lists = [{ option: {}, data: [] }];
  let dataLists = [];
  let legendData = [];
  // 控制显示的项目数
  // let showCount = 10;

  pieDataLists.forEach((item, index) => {
    let { name, value } = item;
    dataLists.push({
      name,
      value
    });
  });

  dataLists = dataLists.sort((a, b) => {
    return b.value - a.value;
  });
  // .slice(0, showCount);

  legendData = dataLists.map((item, index) => {
    let name = item.name == "" ? "未知字段" : item.name;
    return name;
  });

  lists[0].option = {
    radius: ["60", "90"],
    center: ["180", "160"],
    label: {
      position: "inner",
      formatter: function(e) {
        let newValue = Math.ceil(parseFloat(e.percent));
        if (newValue >= 5) {
          return newValue + "%";
        } else {
          return "";
        }
      }
    }
  };

  lists[0].data = dataLists;
  return {
    title: {
      text: titleStr,
      left: "140",
      top: "150",
      textStyle: {
        fontSize: 18,
        fontWeight: 400,
        color: "#1890FF"
      }
    },
    legend: {
      orient: "vertical",
      left: "360",
      top: "80",
      icon: "circle",
      data: legendData,
      textStyle: {
        fontSize: 12,
        fontWeight: 200,
        color: "#000000"
      },
      formatter: params => {
        let str = "";
        dataLists.forEach((itme, index) => {
          if (params == itme.name) {
            str = `${itme.name} : ${itme.value}`;
          }
          return false;
        });

        return str;
      }
    },
    dataLists: lists
  };
}

function buildBarLists(barDataLists, titleStr) {
  let dataLists = [];
  let stateLists = [titleStr];
  let xAxisData = [];

  stateLists.forEach((str, index) => {
    dataLists.push({
      option: {
        label: {
          show: true,
          position: "top"
        }
      },
      data: transformTimeArray(barDataLists)
    });
  });

  xAxisData = barDataLists.map((item, index) => {
    return item.name;
  });

  return {
    title: {
      text: titleStr,
      left: "44",
      top: "24",
      textStyle: {
        fontSize: 18,
        fontWeight: 600,
        color: "#1890FF"
      }
    },
    legend: {
      orient: "horizontal",
      left: "center",
      bottom: "10"
    },
    grid: { left: "60", top: "80", width: "1020" },
    xAxisData,
    lists: dataLists
  };
}

export default {
  name: "ProductRepairStatistics",
  components: {
    Search,
    Pie,
    BarChart
  },
  data() {
    let moment = this.$Moment;
    return {
      role: "",
      compId: "",
      initSearchData: {
        timeType: "本月",
        startTime: `${moment()
          .startOf("month")
          .format("YYYY-MM-DD")} 00:00:00`,
        endTime: `${moment()
          .endOf("month")
          .format("YYYY-MM-DD")} 23:59:59`
      },
      barProductTypeLists: {},
      pieRepairFaultLists: {},
      barRepairStatusLists: {},
      pieRepairResultLists: {}
    };
  },
  methods: {
    // 产品类型
    async getProductTypeData(parames, key) {
      const res = await api.getProductTypeData({
        startTime: parames.startTime,
        endTime: parames.endTime,
        companyId: this.compId
      });
      console.log(res);

      if (res.msgCode !== 0) {
        this.$message.error(`产品类型统计查询异常`);
        return;
      }

      let dataLists = res.data.map((item, index) => {
        let { count, name } = item;
        return {
          name,
          value: count
        };
      });

      this[key] = buildBarLists(dataLists, "产品类型");
    },

    // 故障原因
    async getFaultData(parames, key) {
      const res = await api.getFaultData({
        startTime: parames.startTime,
        endTime: parames.endTime,
        companyId: this.compId
      });
      console.log(res);

      if (res.msgCode !== 0) {
        this.$message.error(`故障原因统计查询异常`);
        return;
      }

      let dataLists = res.data.map((item, index) => {
        let { count, name } = item;
        return {
          name,
          value: count
        };
      });

      this[key] = buildPieData(dataLists, "故障原因");
    },

    // 订单状态
    async getStatusData(parames, key) {
      const res = await api.getStatusData({
        startTime: parames.startTime,
        endTime: parames.endTime,
        companyId: this.compId
      });
      console.log(res);

      if (res.msgCode !== 0) {
        this.$message.error(`订单状态统计查询异常`);
        return;
      }

      let dataLists = res.data.map((item, index) => {
        let { count, name } = item;
        return {
          name: formatStatusType(name),
          value: count
        };
      });

      this[key] = buildBarLists(dataLists, "订单状态");
    },

    // 返修结果
    async getResultData(parames, key) {
      const res = await api.getResultData({
        startTime: parames.startTime,
        endTime: parames.endTime,
        companyId: this.compId
      });
      console.log(res);

      if (res.msgCode !== 0) {
        this.$message.error(`返修结果统计查询异常`);
        return;
      }

      let dataLists = res.data.map((item, index) => {
        let { count, name } = item;
        return {
          name: formatResultType(name),
          value: count
        };
      });

      this[key] = buildPieData(dataLists, "返修结果");
    },

    getData(parames) {
      this.getProductTypeData({ ...parames }, "barProductTypeLists");
      this.getFaultData({ ...parames }, "pieRepairFaultLists");
      this.getStatusData({ ...parames }, "barRepairStatusLists");
      this.getResultData({ ...parames }, "pieRepairResultLists");
    },
    getSearchData(value) {
      this.getData(value);
    },
    getLocalStorageData() {
      const phone = localStorage.getItem("phone");
      this.userName = phone;
      if (!phone) {
        this.$router.push("/");
      }
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      this.role = userInfo.ID;
      this.compId = userInfo.compid;
    },
    callback(key) {}
  },
  created() {
    this.getLocalStorageData();
  },
  mounted() {
    this.getData(this.initSearchData);
  }
};
</script>

<style scoped="scoped">
.main {
  height: 100%;
  width: 100%;
  padding: 0px 0px 0px 0px;
}

.main > .content {
  padding: 16px;
  background: #ecf2f7;
}
</style>
